package com.yanghui.agent.agent.springboot.a.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yanghui.agent.agent.springboot.a.client.IntegralRemoteService;
import com.yanghui.agent.agent.springboot.a.entity.User;
import com.yanghui.agent.agent.springboot.a.mapper.UserMapper;
import com.yanghui.agent.agent.springboot.a.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    private static Jedis jedis;

    static {
        jedis = new Jedis("127.0.0.1", 6379);
    }

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IntegralRemoteService integralRemoteService;

    @Override
    public String login(String name,String password) {
        User user = this.userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName,name));
        if(null == user){
            return "login fail.";
        }
        if(user.getPassword().equals(password)){
            String token = UUID.randomUUID().toString();
            Map<String,Object> result = this.integralRemoteService.query(user.getId());
            user.setNum(Integer.valueOf(result.get("num").toString()));
            jedis.set("token:" + name, JSON.toJSONString(user));
            return token;
        }
        return "login fail.";
    }

    @Override
    @Transactional
    public void testInsert() {
        User user = new User();
        user.setName("admin");
        user.setPassword("123456");
        this.userMapper.insert(user);

        User user1 = new User();
        user1.setName("nick");
        user1.setPassword("123456");
        this.userMapper.insert(user1);
    }

    @Override
    public String testSelect() {
        User user = this.userMapper.selectById(1);
        return JSON.toJSONString(user);
    }

    @Override
    public User queryById(Long id) {
        String us = jedis.get(String.valueOf(id));
        User user;
        if(null == us){
            user = new User();
            user.setId(id);
            user.setName("admin" + id);
            user.setPassword("123456");
            jedis.set(id+"",id + "");
            return user;
        }
        user = new User();
        user.setId(id);
        user.setName("admin" + us);
        user.setPassword("123456");
        return user;
    }
}
